﻿using System.Collections.Concurrent;
using System.Linq;
using System.Threading;
using TitaniumAS.Opc.Client.Da;

namespace MolyMart.WithOPC
{
    public class ValuesWorker
    {
        private readonly BlockingCollection<OpcServer> _blockingQuietQueue;
        private readonly BlockingCollection<OpcServer> _blockingActiveQueue;
        private readonly BlockingCollection<ServerValuesItem> _blockingServerValuesQueue;
        private readonly BlockingCollection<MessageItem> _messageQueue;

        public ValuesWorker(BlockingCollection<OpcServer> blockingQuietQueue, BlockingCollection<OpcServer> blockingActiveQueue, BlockingCollection<ServerValuesItem> blockingServerValuesQueue, BlockingCollection<MessageItem> messageQueue)
        {
            _blockingQuietQueue = blockingQuietQueue;
            _blockingActiveQueue = blockingActiveQueue;
            _blockingServerValuesQueue = blockingServerValuesQueue;
            _messageQueue = messageQueue;
        }

        public void Run()
        {
            while (true)
            {
                var asServer = _blockingActiveQueue.Take();
                if (asServer.OpcDaServer.IsConnected)
                {
                    var valueItem = ReadValues(asServer);
                    _blockingServerValuesQueue.Add(valueItem);
                    _blockingActiveQueue.Add(asServer);
                }
                else
                {
                    _blockingQuietQueue.Add(asServer);
                }
                Thread.Sleep(100);
            }
        }

        private ServerValuesItem ReadValues(OpcServer opcServer)
        {
            opcServer.OpcDaItemValues = opcServer.OpcDaGroup.Read(opcServer.OpcDaGroup.Items, OpcDaDataSource.Device);

            ServerValuesItem returnItem = new ServerValuesItem
            {
                ServerId = opcServer.OpcServerDefinition.Id,
                Values = opcServer.OpcDaItemValues.Select(i => new ValuesItem
                {
                    Name = opcServer.OpcServerDefinition.ValuesNameDictionary[i.Item.ItemId],
                    KeyId = i.Item.ItemId,
                    Value = i.Value.ToString(),
                    Quality = i.Quality.ToString(),
                    TimeStamp = i.Timestamp.ToString(),
                    Format = i.Item.CanonicalDataType.FullName
                }).ToArray()
            };
            return returnItem;

        }
    }
    
}
